import router from './router';
import store from './store';
import { getToken } from '@/utils/auth'; // get token from cookie
import { message } from 'ant-design-vue';
// const whiteList = ['/login', '/']; // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  //   NProgress.start()
  // set page title
  //   document.title = getPageTitle(to.meta.title)

  const hasToken = getToken();

  if (hasToken) {
    //   有token而且跳转login 直接返回首页
    if (to.path === '/login') {
      // next({ path: '/' });
      //   NProgress.done()
    } else {
      // 获取用户信息
      const hasGetUserInfo = store.getters.nickName;
      if (hasGetUserInfo) {
        next();
      } else {
        //   没有用户信息
        try {
          await store.dispatch('getUser');
          next();
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('resetToken');
          message.error(error || 'Has Error');
          next(`/login?redirect=${to.path}`);
          // NProgress.done()
        }
      }
    }
  } else {
    //   has no token
    // 查看是否在白名单
    // if (whiteList.includes(to.path)) {
    //   next();
    // } else {
    //   next(`/login?redirect=${to.path}`);
    //   //   NProgress.done();
    // }
    // has no token
    if (to.meta.requiredLogin) {
      next('/login');
    }
  }
  next();
});

// router.afterEach(() => {
//   // finish progress bar
//   NProgress.done();
// });
